﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DAO;
using Domain;

public partial class login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if(Utils.operadorLogueado != null)
                if(Utils.operadorLogueado is Empresa)
                    Response.Redirect(Utils.SecureRedirect("~/EmpHome.aspx"));
                else
                    Response.Redirect(Utils.SecureRedirect("~/UsrManageSuscripciones.aspx"));
        }
    }
    protected void btn_login_Click(object sender, EventArgs e)
    {
        ul_errores.InnerHtml = string.Empty;

        long usr = 0;
        if (!long.TryParse(txt_username.Text, out usr))
        {
            ul_errores.InnerHtml += "<li class='itemerror'>" + "Debe ingresar un usuario válido" + "</li>";
            return;
        }        

        if (string.IsNullOrEmpty(txt_pass.Text))
        {
            ul_errores.InnerHtml += "<li class='itemerror'>" + "Debe ingresar la contraseña" + "</li>";
            return;
        }

        Operador operador = null;

        if (rbl_perfil.SelectedIndex == 0)
        {
            Usuario user = UsuarioDAO.Traer(usr);
            if (user != null)
            {
                operador = user;
            }            
        }
        else
        {
            Empresa emp = EmpresaDAO.Traer(usr);
            if (emp != null)
            {
                operador = emp;
            }
        }

        if (operador == null)
        {
            ul_errores.InnerHtml += "<li class='itemerror'>" + "El usuario no existe" + "</li>";
            return;
        }
        
        if (operador.Password != txt_pass.Text)
        {
            ul_errores.InnerHtml += "<li class='itemerror'>" + "Datos incorrectos" + "</li>";
            return;
        }

        if (chk_keeplogued.Checked)
        {
            DateTime now = DateTime.Now;
            HttpCookie cookieWrite = new HttpCookie("operador");

            // Set the cookie value.
            cookieWrite.Value = (operador is Usuario ? typeof(Usuario).ToString() : typeof(Empresa).ToString()) + "=" + operador.UserName;

            // Set the cookie expiration date.
            cookieWrite.Expires = now.AddDays(1);

            // Add the cookie.
            Response.Cookies.Add(cookieWrite);
        }

        Utils.operadorLogueado = operador;
        Response.Redirect(Utils.SecureRedirect(operador is Usuario ? "~/UsrManageSuscripciones.aspx" : "~/EmpHome.aspx"));

    }
}
